<template>
    <div class="section-container resumeManagement-container">
        <div class="section-title">{{route.meta.title}}</div>
         <!-- 顶部操作栏 -->
         <div class="section-actions">
          <div class="actions-left">
            <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="searchForm" @onSubmit="handleSearch" />
          </div>
        </div>
        <!-- 简历列表 -->
        <div class="resume-list">
            <RuifoxTable v-loading="tableLoading" v-model:tableData="tableData" :field-list="fieldList" :default-checkbox="true" :default-index="true">
                 <!-- 多选 -->
                <template #default-checkbox="{ element }">
                    <div class="table-div-check">
                    <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
                    </div>
                </template>
                <!-- 申请时间 -->
                <template #applyTime="{ element }"> {{ dayjs(element.applyTime).format('YYYY-MM-DD HH:mm') }}</template>
                <!-- 学历 -->
                <!-- 工作经验 -->
                <!-- 状态 -->
                <template #state="{ element }">
                    <el-tag :type="STATE_MAP[element.state]?.type">
                    {{ STATE_MAP[element.state]?.label || '未知状态' }}
                    </el-tag>
                </template>
                <!-- 操作 -->
                <template #options="{ element }">
                    <div class="table-td-option">
                        <el-button link type="primary" @click="showDetail(element)">详情</el-button>
                        <!-- <el-button link type="primary">安排面试</el-button> -->
                        <el-popconfirm
                            title="请选择审核结果"
                            width="220"
                            confirmButtonText="通过"
                            cancelButtonText="不通过"
                            placement="bottom"
                            @confirm="handleAudit(row, true)"
                            @cancel="handleAudit(row, false)"
                        >
                            <template #reference>
                            <el-button link type="primary">审核</el-button>
                            </template>
                            <template #actions="{ confirm, cancel }">
                            <el-button size="small" type="primary" @click="confirm">通过</el-button>
                            <el-button size="small" type="danger" @click="cancel">不通过</el-button>
                            </template>
                        </el-popconfirm>
                        <el-dropdown>
                          <span class="el-dropdown-link">
                            <i class="iconfont">&#xe78d;</i>
                          </span>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item @click="handleExportRecord(element)">下载</el-dropdown-item>
                              <el-dropdown-item>删除</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                    </div>
                </template>
            </RuifoxTable>
        </div>
        <PaginationView
          :total="queryData.total"
          :pageSize="queryData.pageSize"
          :currentPage="queryData.currentPage"
          :allChoose="isAllChooseBtn"
          :pageChoose="isPageChooseBtn"
          :checkedNum="checkedNum"
          :options="curStateOptions"
          @changeSize="handleSizeChange"
          @currentChange="handleCurrentChange"
          @changePageChoose="handlePageChoose"
          @changeAllChoose="handleAllChoose"
          @cancelChoose="handleResetPagination"
          @invertChoose="handleInvertChoose"
          @refreshList="getTableData"
          @checkOption="handleBatch"
        />
        <!-- 简历详情 -->
        <el-dialog v-model="detailVisible" title="简历详情" width="700px" align-center>
            <FormEcho :formData="curFormConfig" :modelValue="curFormResult" height="70vh" :simple="true" />
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { selectPaperResult, updatePaperResultState } from '@/api/form'
import { 
  selectPageAll, 
  // exportRecord
 } from '@/api/record'
import dayjs from 'dayjs'
import { FormEcho } from '@ruifox-cms/components'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { tableList as mixTable } from '@ruifox-cms/utils'
import axios from 'axios'
import { getToken, getUserInfo } from '@ruifox-cms/utils/src/storage'

const route = useRoute()

const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  // isAllSearch,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectPageAll
})
// 内容列表查询参数
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  // state:99,
  // likeParams: {},
  // equalParams: {}
})
Object.assign(queryData, defaultQueryData)
// 修改常量定义
const DEGREE_MAP = {
  1: { label: '初中及以下', value: '初中及以下' },
  2: { label: '中专/中技', value: '中专/中技' },
  3: { label: '高中', value: '高中' },
  4: { label: '大专', value: '大专' },
  5: { label: '本科', value: '本科' },
  6: { label: '硕士', value: '硕士' },
  7: { label: '博士', value: '博士' }
}
const EXPERIENCE_MAP = {
  1: { label: '应届生', value: '应届生' },
  2: { label: '1-3年', value: '1-3年' },
  3: { label: '3-5年', value: '3-5年' },
  4: { label: '5年以上', value: '5年以上' }
}
const STATE_MAP = {
    0: {label: '待审核', type: 'warning'},
    1: {label: '已通过(还未发出面试邀请)', type: ''},
    2: {label: '未通过', type: 'danger'},
    3: {label: '待接受面试邀请', type: ''},
    4: {label: '已接受面试邀请', type: ''},
    5: {label: '已录用', type: 'success'},
    6: {label: '面试不通过', type: 'danger'}
}
// 修改搜索条件配置
const searchCmpArray = ref([
  { label: '职位名称', key: 'name' },
  { label: '工作经验', key: 'workExperience', form_type: 'select', options: Object.values(EXPERIENCE_MAP) },
  { label: '最高学历', key: 'academicQualification', form_type: 'select', options: Object.values(DEGREE_MAP) },
  { label: '状态', key: 'state', form_type: 'select', options: Object.values(STATE_MAP) }
])

const fieldList = ref([
  { title: '候选人', name: 'seekerName' },
  { title: '申请职位', name: 'postName' },
  { title: '申请时间', name: 'applyTime' },
  { title: '学历', name: 'academicQualification' },
  { title: '工作经验', name: 'workExperience' },
  { title: '状态', name: 'state' },
  { title: '操作', name: 'options' }
])
//获取简历详情
const detailVisible = ref(false)
const curFormConfig = ref({})
const curFormResult = ref({})
const showDetail = async (data) => {
  const res = await selectPaperResult({ id: data.resultId, formId: 41 })
  if (res.code === 20000) {
    curFormConfig.value = res.data
    res.data.formItemList.forEach(item => {
      if (!item.modelValue) return
      curFormResult.value[item.formItemId] = item.modelValue
    })
    detailVisible.value = true
  }
}
//审核简历
// 修改审核处理函数
const handleAudit = async (data, isPass) => {
  try {
    let reason = ''
    if (!isPass) {
      // 不通过时弹出输入框
      const { value } = await ElMessageBox.prompt('请输入不通过原因', '填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value) {
            return '原因不能为空'
          }
          return true
        }
      })
      reason = value
    }

    const res = await updatePaperResultState({
      id: data.resultId,
      state: isPass ? 1 : 2,
      reviewOpinion: reason
    })

    if (res.code === 20000) {
      ElMessage.success('审核成功')
      //获取简历列表
    //   await getApplicationList()
    } else {
      ElMessage.error('审核失败')
    }
  } catch (err) {
    // 用户取消输入原因
  }
}
//导出简历
const params = ref({
  fileName:'',
  postName:'',
  state:null,
  userParams:"'seekerName','academicQualification'"
})
const handleExportRecord = async(data) => {
  params.value.fileName = data.seekerName
  params.value.postName = data.postName
  params.value.state = data.state
  try {
    const res = await axios.get(
     '/recruitment/record/export',
     {
      responseType: 'blob',
        baseURL:  process.env.NODE_ENV == 'development' ? '/recruitment_api' : '/api',
        headers: {
          'userId': getUserInfo() ? getUserInfo().id : null,
          'X-token': getToken() ? getToken() : '',
          'X-Timestamp': Date.now()
        },
        params:params.value
      }
    )
      // 创建 Blob 对象
    const blob = new Blob([res.data], {
      type: res.headers['content-type'],
    });
    
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    // 设置文件名
    if (params.value.fileName) {
      link.download = params.value.fileName;
    } else {
      // 尝试从响应头中获取文件名
      const contentDisposition = res.headers['content-disposition'];
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="(.+)"/);
        if (fileNameMatch && fileNameMatch[1]) {
          link.download = fileNameMatch[1];
        }
      }
    }
    // 触发下载
    link.click();
    // 清理资源
    URL.revokeObjectURL(url);
    link.remove();
    return true;
  }catch (error) {
    console.error('下载文件失败:', error);
    return false;
  }
}
onMounted(() => {
  getTableData()
})
</script>
<style lang="scss" scoped>
.resumeManagement-container {
    .setting-operation {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        .setting-operation-left {
            display: flex;
            gap: 10px;
            flex: 1;
        }
  }
}
</style>